(function () {
    console.log('[联动绑定] 脚本已加载');

    // 检查是否在 iframe 中
    const isInIframe = window !== window.top;
    const isTargetIframe = isInIframe && window.location.hostname === 'admin-daily.hszq.com.cn';

    console.log('[联动绑定] 是否在iframe中:', isInIframe);
    console.log('[联动绑定] 是否在目标iframe中:', isTargetIframe);
    console.log('[联动绑定] 当前URL:', window.location.href);

    // 只在目标 iframe 中执行
    if (!isTargetIframe) {
        console.log('[联动绑定] 不在目标iframe中，跳过执行');
        return;
    }

    function waitForPageReady() {
        return new Promise((resolve) => {
            // 检查页面是否已经完全加载
            if (document.readyState === 'complete') {
                console.log('[联动绑定] iframe页面已完全加载');
                resolve();
                return;
            }

            // 如果页面还在加载，等待 load 事件
            if (document.readyState === 'loading') {
                console.log('[联动绑定] iframe页面仍在加载，等待DOMContentLoaded事件');
                document.addEventListener('DOMContentLoaded', () => {
                    console.log('[联动绑定] iframe DOMContentLoaded事件已触发');
                    // DOMContentLoaded 后再等待一段时间确保页面渲染完成
                    setTimeout(resolve, 500);
                });
            } else {
                // interactive 状态，等待 load 事件
                console.log('[联动绑定] iframe页面交互状态，等待load事件');
                window.addEventListener('load', () => {
                    console.log('[联动绑定] iframe窗口load事件已触发');
                    setTimeout(resolve, 300);
                });
            }
        });
    }

    function waitForElements() {
        return new Promise((resolve) => {
            let attempts = 0;
            const maxAttempts = 50; // 最多尝试 5 秒

            function check() {
                attempts++;
                console.log(`[联动绑定] 检查目标元素，第${attempts}次尝试`);

                // 检查页面是否有预期的元素
                const hasContent = document.querySelector('body > *') &&
                    document.body.children.length > 1;

                // 额外检查是否有你的目标元素（可选）
                const hasModalSystem = document.querySelector('.modal') ||
                    document.querySelector('#form-add-type') ||
                    document.body.innerHTML.length > 1000;

                if (hasContent && hasModalSystem) {
                    console.log('[联动绑定] 目标元素已找到');
                    resolve();
                } else if (attempts >= maxAttempts) {
                    console.warn('[联动绑定] 已达到最大尝试次数，继续执行');
                    resolve();
                } else {
                    setTimeout(check, 100);
                }
            }

            check();
        });
    }

    async function initBinder() {
        try {
            console.log('[联动绑定] 开始初始化');

            // 等待页面完全加载
            await waitForPageReady();

            // 等待关键元素出现
            await waitForElements();

            if (!document.body) {
                console.error('[联动绑定] 等待后body仍不可用');
                return;
            }

            console.log('[联动绑定] 页面准备就绪，开始监听');

            // 定义所有需要绑定的选择器对
            const selectorPairs = [
                { main: '#form-add-type', child: '#form-add-childType', name: '新增表单' },
                { main: '#form-edit-type', child: '#form-edit-childType', name: '编辑表单' },
                { main: '#filter-type', child: '#filter-childType', name: '筛选条件' }
            ];

            const boundMap = new Map();
            let prevHasModalOpen = document.body.classList.contains('modal-open');

            function bindSelectors(container, selectorPair) {
                const mainSelect = container.querySelector(selectorPair.main);
                const childSelect = container.querySelector(selectorPair.child);

                if (!mainSelect || !childSelect) {
                    return null;
                }

                console.log(`[联动绑定] 绑定${selectorPair.name}的联动选择器`);

                const allOptGroups = Array.from(childSelect.querySelectorAll('optgroup'));
                const changeHandler = () => {
                    const selectedType = mainSelect.value;
                    childSelect.innerHTML = '';
                    const matchedGroup = allOptGroups.find(g => g.dataset.type === selectedType);
                    if (matchedGroup) {
                        childSelect.appendChild(matchedGroup.cloneNode(true));
                    }
                };

                mainSelect.addEventListener('change', changeHandler);
                mainSelect.dispatchEvent(new Event('change'));

                return { mainSelect, changeHandler, name: selectorPair.name };
            }

            function bindModal(modal) {
                if (!modal || boundMap.has(modal)) return;

                console.log('[联动绑定] 尝试绑定模态框');

                const bindings = [];
                selectorPairs.forEach(pair => {
                    const binding = bindSelectors(modal, pair);
                    if (binding) {
                        bindings.push(binding);
                    }
                });

                if (bindings.length > 0) {
                    boundMap.set(modal, bindings);
                    console.log(`[联动绑定] 模态框绑定成功，共绑定${bindings.length}组选择器`);
                } else {
                    console.warn('[联动绑定] 模态框中未找到目标选择器，跳过');
                }
            }

            function bindPageSelectors() {
                console.log('[联动绑定] 尝试绑定页面级选择器');

                selectorPairs.forEach(pair => {
                    const binding = bindSelectors(document, pair);
                    if (binding) {
                        // 为页面级选择器创建特殊标识
                        const pageKey = `page-${pair.name}`;
                        boundMap.set(pageKey, [binding]);
                        console.log(`[联动绑定] 页面级${pair.name}绑定成功`);
                    }
                });
            }

            function unbindAll() {
                boundMap.forEach((bindings, key) => {
                    bindings.forEach(({ mainSelect, changeHandler, name }) => {
                        mainSelect.removeEventListener('change', changeHandler);
                        console.log(`[联动绑定] 解绑${name}选择器`);
                    });
                });
                boundMap.clear();
            }

            function handleModalOpen() {
                document.querySelectorAll('.modal.in').forEach(modal => {
                    if (!boundMap.has(modal)) bindModal(modal);
                });
            }

            // 初始化时绑定页面级选择器
            bindPageSelectors();

            const bodyObserver = new MutationObserver(() => {
                const curHas = document.body.classList.contains('modal-open');
                if (curHas && !prevHasModalOpen) {
                    console.log('[联动绑定] 检测到模态框打开');
                    setTimeout(handleModalOpen, 150);
                } else if (!curHas && prevHasModalOpen) {
                    console.log('[联动绑定] 检测到模态框关闭');
                    // 只解绑模态框相关的绑定，保留页面级绑定
                    setTimeout(() => {
                        const modalKeys = Array.from(boundMap.keys()).filter(key =>
                            typeof key !== 'string' || !key.startsWith('page-')
                        );
                        modalKeys.forEach(key => {
                            const bindings = boundMap.get(key);
                            bindings.forEach(({ mainSelect, changeHandler, name }) => {
                                mainSelect.removeEventListener('change', changeHandler);
                                console.log(`[联动绑定] 解绑模态框${name}选择器`);
                            });
                            boundMap.delete(key);
                        });
                    }, 150);
                }
                prevHasModalOpen = curHas;
            });

            bodyObserver.observe(document.body, { attributes: true, attributeFilter: ['class'] });

            console.log('[联动绑定] 初始化完成，正在监听body.class变化');

        } catch (error) {
            console.error('[联动绑定] 初始化失败:', error);
        }
    }

    // 入口 - 使用异步初始化
    initBinder();
})();